// Modules to control application life and create native browser window
const {app, BrowserWindow, Menu, ipcMain} = require('electron')
const path = require('path')
const SerialPort = require('serialport');

const gotTheLock = app.requestSingleInstanceLock()
let mainWindow = null
let interval = 100

ipcMain.on('refresh', (e) => {
    SerialPort.list().then(function (data) {
        e.sender.send('com_list', {
            com: data
        })
    });
})

ipcMain.on('config', (e, msg) => {
    const serialPort = new SerialPort(msg.port, {
        baudRate: 9600,
        autoOpen: false
    })

    serialPort.open(function (err) {
        if (!err) {
            e.sender.send('success', {
                'step': 0
            })

            const buf1 = new Buffer("7E00080100007CABCD", "hex")
            const buf2 = new Buffer("7E00080100077FABCD", "hex")
            const buf3 = new Buffer("7E000801000AC0ABCD", "hex")
            const buf4 = new Buffer("7E000801000B20ABCD", "hex")
            const buf5 = new Buffer("7E000801000E04ABCD", "hex")
            const buf6 = new Buffer("7E000801000D00ABCD", "hex")
            const buf7 = new Buffer("7E000801002C00ABCD", "hex")
            const buf8 = new Buffer("7E000801003301ABCD", "hex")
            const buf9 = new Buffer("7E000801000054ABCD", "hex")
            const buf10 = new Buffer("7E000901000000DEC8", "hex")
            const items = [buf1, buf2, buf3, buf4, buf5, buf6, buf7, buf8, buf9, buf10]

            let i = 0
            write_hex(items[i])

            function write_hex(hex) {
                serialPort.write(hex, function (error) {
                    if (error) {
                        e.sender.send('error', {
                            'step': i + 1
                        })
                        return;
                    } else {
                        e.sender.send('success', {
                            'step': i + 1
                        })
                    }
                    if (++i === items.length) {
                        serialPort.close()
                        return;
                    }
                    setTimeout(function () {
                        write_hex(items[i])
                    }, interval)
                })
            }
        } else {
            e.sender.send('error', {
                'step': 0
            })
        }
    })
})

function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        resizable: false,
        width: 300,
        height: 390,
        icon: path.join(__dirname, './img/icon.ico'),
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true
        }
    })

    // and load the index.html of the app.
    mainWindow.loadFile('index.html')

    // Open the DevTools.
    // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    // Hide Menu
    Menu.setApplicationMenu(null)

    createWindow()

    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

// Single Mode
if (gotTheLock) {
    app.on('second-instance', () => {
        if (mainWindow) {
            mainWindow.show()
        }
    })
} else {
    app.exit()
}
